package com.canbot.u05;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;

import com.canbot.u05.activity.MyRobotActivity;
import com.canbot.u05.api.RobotManager;
import com.canbot.u05.bean.CustomDialogue;
import com.canbot.u05.bean.StandbyVoice;
import com.canbot.u05.utils.Config;
import com.canbot.u05.utils.CrashHandler;
import com.canbot.u05.utils.MyDbUtils;
import com.canbot.u05.utils.VolleyUtil;
import com.canbot.u05.versionupdate.UpdateConfig;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * @author Administrator
 */
public class MainApplication extends Application implements Application.ActivityLifecycleCallbacks {

        private static final String TAG = "MainApplication";

      //  private MulticastSocket ds;

      //  private String multicastHost = "224.0.0.1";

      //  private InetAddress receiveAddress;

        /**
         * 是否三方联网成功.//是否连接成功
         */
    //    public static boolean isConnect = false;

        /**
         * 是否下载成功
         */

        public boolean downLoadSuccess = false;

        /**
         * 是否点击断开机器人
         */
       // public static boolean clickDisconnectButton = false;

     //   public static String ACTION_CONNECT_SUCCESS = "com.canbot.u05.isConnect";

        public ArrayList<StandbyVoice> mStandbyVoices = new ArrayList<>();

        public ArrayList<CustomDialogue> mCustomDialogues;

        public static MainApplication mainApplication;

        public static String token;

        public static MainApplication getInstance() {
                return mainApplication;
        }

        public static ImageLoader instance = ImageLoader.getInstance();

        @Override
        public void onCreate() {
                super.onCreate();
                mainApplication = this;
                CrashHandler.getInstance().init(this);
                RobotManager.getInstance().init(this);
                VolleyUtil.initVolley(this);

                //初始化universal image loader
                DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
                        .showImageForEmptyUri(R.drawable.ic_picture_loadfailed)
                        .showImageOnFail(R.drawable.ic_picture_loadfailed)
                        .cacheInMemory(true)
                        .cacheOnDisk(true)
                        .build();
                ImageLoaderConfiguration config = new ImageLoaderConfiguration
                        .Builder(getApplicationContext())
                        .defaultDisplayImageOptions(defaultOptions)
                        .writeDebugLogs()
                        .build();
                instance.init(config);
                this.registerActivityLifecycleCallbacks(this);


//                parseVcc();// 解析自定义对话

                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                        getProperties();
                } else {
                        this.registerReceiver(new BroadcastReceiver() {

                                @Override
                                public void onReceive(Context context, Intent intent) {
                                        getProperties();
                                }
                        }, new IntentFilter(Intent.ACTION_MEDIA_MOUNTED));
                }

        }

        private void getProperties() {
                final Properties p = new Properties();
                try {
                        final FileInputStream in = new FileInputStream(Environment.getExternalStorageDirectory().toString()
                                + "/ai/config.properties");
                        p.load(new InputStreamReader(in, "utf-8"));
                        in.close();
                } catch (FileNotFoundException e) {
                        e.printStackTrace();
                } catch (IOException e) {
                        e.printStackTrace();
                }

                //修改机器人的名字
                final String robotname = p.getProperty("robotname");
                if (!TextUtils.isEmpty(robotname)) {
                        Config.ROBOT_NAME = robotname;
                }

                //修改机器人自身热点名称前缀
                final String robotWifiNamePre = p.getProperty("robotWifiNamePrefix");
                if (!TextUtils.isEmpty(robotWifiNamePre)) {
                        Config.ROBOT_WIFI_NAME_PREFiX = robotWifiNamePre;
                }

                //修改机器人自身热点密码
                final String robotWifiPwd = p.getProperty("robotWifiPassword");
                if (!TextUtils.isEmpty(robotWifiPwd)) {
                        Config.ROBOT_WIFI_PASSWORD = robotWifiPwd;
                }

                //修改地图方案 步科思 slam
                final String isBuKeSi = p.getProperty("isBuKeSi");
                if (!TextUtils.isEmpty(isBuKeSi)) {
                        Config.isBuKeSi = Boolean.valueOf(isBuKeSi);
                }
                // ai版本号
                String aiVersion = p.getProperty("version");
                if (!TextUtils.isEmpty(aiVersion)) {
                        UpdateConfig.aiVersionCode = aiVersion;
                }

        }

//        /**
//         * 解析 自定义对话
//         */
//        private void parseVcc() {
//                mCustomDialogues = MyDbUtils.queryAll(this);
//        }



        private boolean flag;




        /**
         * 判断mainactivity是否处于栈顶
         *
         * @return true在栈顶false不在栈顶
         */
        private boolean isMainActivityTop() {
                ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
                String name = manager.getRunningTasks(1).get(0).topActivity.getClassName();
                return name.equals(MyRobotActivity.class.getName());
        }

        @Override
        public void onTrimMemory(int level) {
                super.onTrimMemory(level);
        }

        @Override
        public void onTerminate() {
                super.onTerminate();
        }

        static List<Activity> activitiesList = new ArrayList<>();

        @Override
        public void onActivityCreated(Activity activity, Bundle bundle) {
                activitiesList.add(activity);
        }

        @Override
        public void onActivityStarted(Activity activity) {

        }

        @Override
        public void onActivityResumed(Activity activity) {

        }

        @Override
        public void onActivityPaused(Activity activity) {

        }

        @Override
        public void onActivityStopped(Activity activity) {

        }

        @Override
        public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {

        }

        @Override
        public void onActivityDestroyed(Activity activity) {
                if (null != activitiesList && null != activity) {
                        activitiesList.remove(activity);
                }
        }

        /**
         * 销毁Activity
         *
         * @param name
         */
        public static void finishActivity(String name) {
                if (activitiesList != null && activitiesList.size() != 0) {
                        for (Activity activity : activitiesList) {
                                String className = activity.getClass().toString();
                                if (className.contains(name)) {
                                        activity.finish();
                                }
                        }
                }
        }

}
